<?php

namespace app\api\controller;

use app\api\model\VolleyDesc as Balance;
use app\api\model\YaoqingRecords as Income;
use think\Db;

class Exchange extends Common
{
    public function lists()
    {
        $data = Db::name('exchange_style')
            ->field('id, icon, price, money')
            ->where(['is_hidden' => 0])
            ->order('sort desc, id asc')->select();

        foreach ($data as $key => $item) {
            $data[$key]['icon'] = changeUrl($item['icon']);
            $data[$key]['price'] =  sprintf("%.0f", $item['price']);
            $data[$key]['money'] =  sprintf("%.0f", $item['money']);
        }

        return $this->pass($data);
    }

    public function index()
    {
        $exchangeStyle = Db::name('exchange_style')->find($this->params['id']);

        if (!$exchangeStyle) return $this->return['exchange.error.notExist'];
        if ($exchangeStyle['is_hidden']) return $this->return['exchange.error.isHidden'];

        if ($exchangeStyle['price'] > $this->member['volley']) {
            return $this->return['user.error.insufficientBalance'];
        }

        Balance::index($this->member['id'], $exchangeStyle['price'], '金币兑换积分');
        Income::index($this->member['id'], $this->member['id'], $exchangeStyle['money'], '金币兑换积分', 1);

        return $this->return['exchange.success.default'];
    }
}
